import { Message } from 'element-ui'

export const serial = function (usePastPorts?: boolean) {
  if (usePastPorts === undefined) usePastPorts = false
  return new Promise(async resolve => {
    const navi = navigator as any
    const ports = await navi.serial.getPorts()
    const port = ports.length === 0 || usePastPorts ? await navi.serial.requestPort() : ports[0]
    await port.open({ baudRate: 57600 })
    port.onconnect = function () {
      Message({
        message: 'COM口已连接',
        type: 'success'
      })
    }
    port.ondisconnect = function () {
      Message({
        message: 'COM口连接断开',
        type: 'warning'
      })
    }
    let result: Uint8Array = new Uint8Array()
    while (port.readable) {
      const reader = await port.readable.getReader()
      try {
        while (true) {
          const { value, done } = await reader.read()
          result = concatUintArray(result, value)
          if ([13, 9, 10].includes(value[value.length - 1])) {
            // 13 - enter
            // 9  - tab
            // 10 - LF
            await reader.releaseLock()
            await port.close()
            resolve(result)
            break
            // await port.close()
          }
          if (done) {
            reader.releaseLock()
            break
          }
        }
      } catch (error) {
        console.log(error)
      } finally {
        reader.releaseLock()
      }
    }
  })
}

function concatUintArray(target: Uint8Array, curr: Uint8Array) {
  const arr = [...target, ...curr]
  return new Uint8Array(arr)
}
